home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 August: Tool Chest / Dev.CD Aug 94.toast / Tool Chest / Graphics & Imaging / Virtual Sphere 1.0.1 / Virtual Sphere Sample Code 1.1 / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-25  |  29.2 KB  |  846 lines  |  [TEXT/MPS ]

  1. /*•••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
  2. /* Sample.c
  3. /*
  4. /* Modified for Virtual Sphere Sample Code Release v1.1
  5. /*
  6. /* Author: Michael Chen, Human Interface Group / ATG
  7. /* Copyright © 1991-1993 Apple Computer, Inc.  All rights reserved.
  8. /*•••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••*/
  9. /*------------------------------------------------------------------------------
  10. #
  11. #    Apple Macintosh Developer Technical Support
  12. #
  13. #    MultiFinder-Aware Simple Sample Application
  14. #
  15. #    Sample
  16. #
  17. #    Sample.c    -    C Source
  18. #
  19. #    Copyright © Apple Computer, Inc. 1989-1990
  20. #    All rights reserved.
  21. #
  22. #    Versions:    
  23. #                1.00                08/88
  24. #                1.01                11/88
  25. #                1.02                04/89    MPW 3.1
  26. #                1.03                02/90    MPW 3.2
  27. #
  28. #    Components:
  29. #                Sample.c            Feb.  1, 1990
  30. #                Sample.r            Feb.  1, 1990
  31. #                Sample.h            Feb.  1, 1990
  32. #                Sample.make            Feb.  1, 1990
  33. #
  34. #    Sample is an example application that demonstrates how to
  35. #    initialize the commonly used toolbox managers, operate 
  36. #    successfully under MultiFinder, handle desk accessories, 
  37. #    and create, grow, and zoom windows.
  38. #
  39. #    It does not by any means demonstrate all the techniques 
  40. #    you need for a large application. In particular, Sample 
  41. #    does not cover exception handling, multiple windows/documents, 
  42. #    sophisticated memory management, printing, or undo. All of 
  43. #    these are vital parts of a normal full-sized application.
  44. #
  45. #    This application is an example of the form of a Macintosh 
  46. #    application; it is NOT a template. It is NOT intended to be 
  47. #    used as a foundation for the next world-class, best-selling, 
  48. #    600K application. A stick figure drawing of the human body may 
  49. #    be a good example of the form for a painting, but that does not 
  50. #    mean it should be used as the basis for the next Mona Lisa.
  51. #
  52. #    We recommend that you review this program or TESample before 
  53. #    beginning a new application.
  54. #
  55. ------------------------------------------------------------------------------*/
  56.  
  57.  
  58. /* Segmentation strategy:
  59.  
  60.    This program consists of three segments. Main contains most of the code,
  61.    including the MPW libraries, and the main program. Initialize contains
  62.    code that is only used once, during startup, and can be unloaded after the
  63.    program starts. %A5Init is automatically created by the Linker to initialize
  64.    globals for the MPW libraries and is unloaded right away. */
  65.  
  66.  
  67. /* SetPort strategy:
  68.  
  69.    Toolbox routines do not change the current port. In spite of this, in this
  70.    program we use a strategy of calling SetPort whenever we want to draw or
  71.    make calls which depend on the current port. This makes us less vulnerable
  72.    to bugs in other software which might alter the current port (such as the
  73.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  74.    Hopefully, this also makes the routines from this program more self-contained,
  75.    since they don't depend on the current port setting. */
  76.  
  77. #ifndef __GLOBALS__
  78. #include "Globals.h"
  79. #endif
  80.  
  81. /*------------------------------------------------------------------------------*/
  82. #ifdef THINK_C
  83.  
  84. #ifndef __TRAPS__
  85. #include <Traps.h>
  86. #endif
  87.  
  88. #ifndef __VALUES__
  89. #include <Values.h>
  90. #endif
  91.  
  92.  
  93. #endif THINK_C
  94. /*------------------------------------------------------------------------------*/
  95. #ifdef applec
  96. #include <Values.h>
  97. #include <Types.h>
  98. #include <Resources.h>
  99. #include <QuickDraw.h>
  100. #include <Fonts.h>
  101. #include <Events.h>
  102. #include <Windows.h>
  103. #include <Menus.h>
  104. #include <TextEdit.h>
  105. #include <Dialogs.h>
  106. #include <Desk.h>
  107. #include <ToolUtils.h>
  108. #include <Memory.h>
  109. #include <SegLoad.h>
  110. #include <Files.h>
  111. #include <OSUtils.h>
  112. #include <OSEvents.h>
  113. #include <DiskInit.h>
  114. #include <Packages.h>
  115. #include <Traps.h>
  116. #endif applec
  117. /*------------------------------------------------------------------------------*/
  118.  
  119. #include "Sample.h"                /* bring in all the #defines for Sample */
  120.  
  121. #ifndef    __SAMPLEADDITIONAL__
  122. #include "SampleAdditional.h"
  123. #endif
  124.  
  125. /* The "g" prefix is used to emphasize that a variable is global. */
  126.  
  127. /* GMac is used to hold the result of a SysEnvirons call. This makes
  128.    it convenient for any routine to check the environment. */
  129. SysEnvRec    gMac;                /* set up by Initialize */
  130.  
  131. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  132.    trap is available. If it is false, we know that we must call GetNextEvent. */
  133. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  134.  
  135. /* GInBackground is maintained by our osEvent handling routines. Any part of
  136.    the program can check it to find out if it is currently in the background. */
  137. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  138.  
  139.  
  140. /* The following globals are the state of the window. If we supported more than
  141.    one window, they would be attatched to each document, rather than globals. */
  142.  
  143.  
  144.  
  145.  
  146. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  147.    actual prototypes for parameter type checking. */
  148. void EventLoop( void );
  149. void DoEvent( EventRecord *event );
  150. void AdjustCursor( Point mouse, RgnHandle region );
  151. void GetGlobalMouse( Point *mouse );
  152. void DoUpdate( WindowPtr window );
  153. void DoActivate( WindowPtr window, Boolean becomingActive );
  154.  
  155. /*void DoContentClick( WindowPtr window );                                <MC> */
  156.  
  157. void DrawWindow( WindowPtr window );
  158. void AdjustMenus( void );
  159. void DoMenuCommand( long menuResult );
  160. Boolean DoCloseWindow( WindowPtr window );
  161. void Terminate( void );
  162. void Initialize( void );
  163. Boolean GoGetRect( short rectID, Rect *theRect );
  164. void ForceEnvirons( void );
  165. Boolean IsAppWindow( WindowPtr window );
  166. Boolean IsDAWindow( WindowPtr window );
  167. Boolean TrapAvailable( short tNumber, TrapType tType );
  168. void AlertUser( void );
  169.  
  170.  
  171. /* Define HiWrd and LoWrd macros for efficiency. */
  172. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  173. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  174.  
  175. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  176.    dependency on the ordering of fields within a Rect */
  177. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  178. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  179.  
  180.  
  181. #ifdef applec
  182. extern void _DataInit();
  183. #endif applec
  184.  
  185. /* This routine is part of the MPW runtime library. This external
  186.    reference to it is done so that we can unload its segment, %A5Init. */
  187.  
  188.  
  189. #pragma segment Main
  190. main()
  191. {
  192.     #ifdef applec
  193.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  194.     #endif applec
  195.     
  196.     /* 1.01 - call to ForceEnvirons removed */
  197.     
  198.     /*    If you have stack requirements that differ from the default,
  199.         then you could use SetApplLimit to increase StackSpace at 
  200.         this point, before calling MaxApplZone. */
  201.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  202.  
  203.     Initialize();                    /* initialize the program */
  204.  
  205.     #ifdef applec
  206.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  207.     #endif applec
  208.  
  209.     EventLoop();                    /* call the main event loop */
  210.     
  211.     CleanUp3D ();                    /* <MC> */
  212. }
  213.  
  214.  
  215. /*    Get events forever, and handle them by calling DoEvent.
  216.     Get the events by calling WaitNextEvent, if it's available, otherwise
  217.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  218.  
  219. #pragma segment Main
  220. void EventLoop()
  221. {
  222.     RgnHandle    cursorRgn;
  223.     Boolean        gotEvent;
  224.     EventRecord    event;
  225.     Point        mouse;
  226.  
  227.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  228.     do {
  229.         /* use WNE if it is available */
  230.         if ( gHasWaitNextEvent ) {
  231.             GetGlobalMouse(&mouse);
  232.             AdjustCursor(mouse, cursorRgn);
  233.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  234.         }
  235.         else {
  236.             SystemTask();
  237.             gotEvent = GetNextEvent(everyEvent, &event);
  238.         }
  239.         if ( gotEvent ) {
  240.             /* make sure we have the right cursor before handling the event */
  241.             AdjustCursor(event.where, cursorRgn);
  242.             DoEvent(&event);
  243.         }
  244.         /*    If you are using modeless dialogs that have editText items,
  245.             you will want to call IsDialogEvent to give the caret a chance
  246.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  247.             for a non-NIL value before calling IsDialogEvent. */
  248.     } while ( true );    /* loop forever; we quit via ExitToShell */
  249. } /*EventLoop*/
  250.  
  251.  
  252. /* Do the right thing for an event. Determine what kind of event it is, and call
  253.  the appropriate routines. */
  254.  
  255. #pragma segment Main
  256. void DoEvent(event)
  257.     EventRecord    *event;
  258. {
  259.     short        part, err;
  260.     WindowPtr    window;
  261.     Boolean        hit;
  262.     char        key;
  263.     Point        aPoint;
  264.  
  265.     switch ( event->what ) {
  266.         case mouseDown:
  267.             part = FindWindow(event->where, &window);
  268.             switch ( part ) {
  269.                 case inMenuBar:                /* process a mouse menu command (if any) */
  270.                     AdjustMenus();
  271.                     DoMenuCommand(MenuSelect(event->where));
  272.                     break;
  273.                 case inSysWindow:            /* let the system handle the mouseDown */
  274.                     SystemClick(event, window);
  275.                     break;
  276.                 case inContent:
  277.                     if ( window != FrontWindow() ) {
  278.                         SelectWindow(window);
  279.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  280.                     } else
  281.                         DoContentClick(window, event);        /* <MC> */
  282.                     break;
  283.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  284.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  285.                     InvalRect(&window->portRect);    /* Causes a check to see if GWorld needs to be reallocated <MC> */
  286.                     break;
  287.                 case inGrow:
  288.                     InvalRect(&window->portRect);    /* Causes a check to see if GWorld needs to be reallocated <MC> */
  289.                     break;
  290.                 case inZoomIn:
  291.                 case inZoomOut:
  292.                     hit = TrackBox(window, event->where, part);
  293.                     if ( hit ) {
  294.                         SetPort(window);                /* the window must be the current port... */
  295.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  296.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  297.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  298.                     }
  299.                     break;
  300.             }
  301.             break;
  302.         case keyDown:
  303.         case autoKey:                        /* check for menukey equivalents */
  304.             key = event->message & charCodeMask;
  305.             if ( event->modifiers & cmdKey )            /* Command key down */
  306.                 if ( event->what == keyDown ) {
  307.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  308.                     DoMenuCommand(MenuKey(key));
  309.                 }
  310.             break;
  311.         case activateEvt:
  312.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  313.             break;
  314.         case updateEvt:
  315.             DoUpdate((WindowPtr) event->message);
  316.             break;
  317.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  318.             to a diskEvt, so that the user can format a floppy. */
  319.         case diskEvt:
  320.             if ( HiWord(event->message) != noErr ) {
  321.                 SetPt(&aPoint, kDILeft, kDITop);
  322.                 err = DIBadMount(aPoint, event->message);
  323.             }
  324.             break;
  325.         case kOSEvent:
  326.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  327.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  328.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  329.                     gInBackground = (event->message & kResumeMask) == 0;
  330.                     DoActivate(FrontWindow(), !gInBackground);
  331.                     break;
  332.             }
  333.             break;
  334.     }
  335. } /*DoEvent*/
  336.  
  337.  
  338. /*    Change the cursor's shape, depending on its position. This also calculates the region
  339.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  340.     that region, an event would be generated, causing this routine to be called,
  341.     allowing us to change the region to the region the mouse is currently in. If
  342.     there is more to the event than just “the mouse moved”, we get called before the
  343.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  344.     this is called again before we     fall back into WNE. */
  345.  
  346. #pragma segment Main
  347. void AdjustCursor(mouse,region)
  348.     Point        mouse;
  349.     RgnHandle    region;
  350. {
  351.     WindowPtr    window;
  352.     RgnHandle    arrowRgn;
  353.     RgnHandle    plusRgn;
  354.     Rect        globalPortRect;
  355.  
  356.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  357.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  358.         /* calculate regions for different cursor shapes */
  359.         arrowRgn = NewRgn();
  360.         plusRgn = NewRgn();
  361.  
  362.         /* start with a big, big rectangular region */
  363.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  364.  
  365.         /* calculate plusRgn */
  366.         if ( IsAppWindow(window) ) {
  367.             SetPort(window);    /* make a global version of the viewRect */
  368.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  369.             globalPortRect = window->portRect;
  370.             RectRgn(plusRgn, &globalPortRect);
  371.             SectRgn(plusRgn, window->visRgn, plusRgn);
  372.             SetOrigin(0, 0);
  373.         }
  374.  
  375.         /* subtract other regions from arrowRgn */
  376.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  377.  
  378.         /* change the cursor and the region parameter */
  379.         if ( PtInRgn(mouse, plusRgn) ) {
  380.             SetCursor(*GetCursor(plusCursor));
  381.             CopyRgn(plusRgn, region);
  382.         } else {
  383.             SetCursor(&qd.arrow);
  384.             CopyRgn(arrowRgn, region);
  385.         }
  386.  
  387.         /* get rid of our local regions */
  388.         DisposeRgn(arrowRgn);
  389.         DisposeRgn(plusRgn);
  390.     }
  391. } /*AdjustCursor*/
  392.  
  393.  
  394. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  395.     it will return either a pending event or a null event. In either case,
  396.     the where field of the event record will contain the current position
  397.     of the mouse in global coordinates and the modifiers field will reflect
  398.     the current state of the modifiers. Another way to get the global
  399.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  400.     being sure that thePort is set to a valid port. */
  401.  
  402. #pragma segment Main
  403. void GetGlobalMouse(mouse)
  404.     Point    *mouse;
  405. {
  406.     EventRecord    event;
  407.     
  408.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  409.     *mouse = event.where;                /* just the mouse position */
  410. } /*GetGlobalMouse*/
  411.  
  412.  
  413. /*    This is called when an update event is received for a window.
  414.     It calls DrawWindow to draw the contents of an application window.
  415.     As an effeciency measure that does not have to be followed, it
  416.     calls the drawing routine only if the visRgn is non-empty. This
  417.     will handle situations where calculations for drawing or drawing
  418.     itself is very time-consuming. */
  419.  
  420. #pragma segment Main
  421. void DoUpdate(window)
  422.     WindowPtr    window;
  423. {
  424.     if ( IsAppWindow(window) ) {
  425.         UpdateWindow(window);            /* <MC> */
  426.     }
  427. } /*DoUpdate*/
  428.  
  429.  
  430. /*    This is called when a window is activated or deactivated.
  431.     In Sample, the Window Manager's handling of activate and
  432.     deactivate events is sufficient. Other applications may have
  433.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  434.  
  435. #pragma segment Main
  436. void DoActivate (WindowPtr window, Boolean becomingActive)
  437. {
  438.     if ( IsAppWindow(window) ) {
  439.         if ( becomingActive )
  440.             /* do whatever you need to at activation */ ;
  441.         else
  442.             /* do whatever you need to at deactivation */ ;
  443.     }
  444. } /*DoActivate*/
  445.  
  446.  
  447.  
  448. /*    Enable and disable menus based on the current state.
  449.     The user can only select enabled menu items. We set up all the menu items
  450.     before calling MenuSelect or MenuKey, since these are the only times that
  451.     a menu item can be selected. Note that MenuSelect is also the only time
  452.     the user will see menu items. This approach to deciding what enable/
  453.     disable state a menu item has the advantage of concentrating all
  454.     the decision-making in one routine, as opposed to being spread throughout
  455.     the application. Other application designs may take a different approach
  456.     that is just as valid. */
  457.  
  458. #pragma segment Main
  459. void AdjustMenus()
  460. {
  461.     WindowPtr    window;
  462.     MenuHandle    menu;
  463.  
  464.     window = FrontWindow();
  465.  
  466.     menu = GetMHandle(mFile);
  467.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  468.         EnableItem(menu, iClose);
  469.     else
  470.         DisableItem(menu, iClose);    /* but not our traffic light window */
  471.  
  472.     menu = GetMHandle(mEdit);
  473.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  474.         EnableItem(menu, iUndo);
  475.         EnableItem(menu, iCut);
  476.         EnableItem(menu, iCopy);
  477.         EnableItem(menu, iClear);
  478.         EnableItem(menu, iPaste);
  479.     } else {                        /* …but we don’t use it */
  480.         DisableItem(menu, iUndo);
  481.         DisableItem(menu, iCut);
  482.         DisableItem(menu, iCopy);
  483.         DisableItem(menu, iClear);
  484.         DisableItem(menu, iPaste);
  485.     }
  486.  
  487.     AdjustAdditionalMenus ();        /* new <MC> */
  488.     
  489. } /*AdjustMenus*/
  490.  
  491.  
  492. /*    This is called when an item is chosen from the menu bar (after calling
  493.     MenuSelect or MenuKey). It performs the right operation for each command.
  494.     It is good to have both the result of MenuSelect and MenuKey go to
  495.     one routine like this to keep everything organized. */
  496.  
  497. #pragma segment Main
  498. void DoMenuCommand(menuResult)
  499.     long        menuResult;
  500. {
  501.     short        menuID;                /* the resource ID of the selected menu */
  502.     short        menuItem;            /* the item number of the selected menu */
  503.     short        itemHit;
  504.     Str255        daName;
  505.     short        daRefNum;
  506.     Boolean        handledByDA;
  507.  
  508.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  509.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  510.     switch ( menuID ) {
  511.         case mApple:
  512.             switch ( menuItem ) {
  513.                 case iAbout:        /* bring up alert for About */
  514.                     itemHit = Alert(rAboutAlert, nil);
  515.                     break;
  516.                 default:            /* all non-About items in this menu are DAs */
  517.                     /* type Str255 is an array in MPW 3 */
  518.                     GetItem(GetMHandle(mApple), menuItem, daName);
  519.                     daRefNum = OpenDeskAcc(daName);
  520.                     break;
  521.             }
  522.             break;
  523.         case mFile:
  524.             switch ( menuItem ) {
  525.                 case iClose:
  526.                     DoCloseWindow(FrontWindow());
  527.                     break;
  528.                 case iQuit:
  529.                     Terminate();
  530.                     break;
  531.             }
  532.             break;
  533.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  534.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  535.             break;
  536.     }
  537.     
  538.     DoAdditionalMenuCommand (menuResult);    /* New <MC> */
  539.  
  540.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  541. } /*DoMenuCommand*/
  542.  
  543.  
  544.  
  545. /* Close a window. This handles desk accessory and application windows. */
  546.  
  547. /*    1.01 - At this point, if there was a document associated with a
  548.     window, you could do any document saving processing if it is 'dirty'.
  549.     DoCloseWindow would return true if the window actually closed, i.e.,
  550.     the user didn’t cancel from a save dialog. This result is handy when
  551.     the user quits an application, but then cancels the save of a document
  552.     associated with a window. */
  553.  
  554. #pragma segment Main
  555. Boolean DoCloseWindow(window)
  556.     WindowPtr    window;
  557. {
  558.     if ( IsDAWindow(window) )
  559.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  560.     else if ( IsAppWindow(window) )
  561.         CloseWindow(window);
  562.     return true;
  563. } /*DoCloseWindow*/
  564.  
  565.  
  566. /**************************************************************************************
  567. *** 1.01 DoCloseBehind(window) was removed ***
  568.  
  569.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  570.     and not having to worry about updating the windows, but it suffered
  571.     from a fatal flaw. If a desk accessory owned two windows, it would
  572.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  573.     got around to calling DoCloseWindow for that other window that was already
  574.     closed, things would go very poorly. Another option would be to have a
  575.     procedure, GetRearWindow, that would go through the window list and return
  576.     the last window. Instead, we decided to present the standard approach
  577.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  578.     has a potential benefit in that the window whose document needs to be saved
  579.     may be visible since it is the front window, therefore decreasing the
  580.     chance of user confusion. For aesthetic reasons, the windows in the
  581.     application should be checked for updates periodically and have the
  582.     updates serviced.
  583. **************************************************************************************/
  584.  
  585.  
  586. /* Clean up the application and exit. We close all of the windows so that
  587.  they can update their documents, if any. */
  588.  
  589. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  590.     shell, but will return instead. */
  591.  
  592. #pragma segment Main
  593. void Terminate()
  594. {
  595.     WindowPtr    aWindow;
  596.     Boolean        closed;
  597.     
  598.     closed = true;
  599.     do {
  600.         aWindow = FrontWindow();                /* get the current front window */
  601.         if (aWindow != nil)
  602.             closed = DoCloseWindow(aWindow);    /* close this window */    
  603.     }
  604.     while (closed && (aWindow != nil));
  605.     if (closed)
  606.         ExitToShell();                            /* exit if no cancellation */
  607. } /*Terminate*/
  608.  
  609.  
  610. /*    Set up the whole world, including global variables, Toolbox managers,
  611.     and menus. We also create our one application window at this time.
  612.     Since window storage is non-relocateable, how and when to allocate space
  613.     for windows is very important so that heap fragmentation does not occur.
  614.     Because Sample has only one window and it is only disposed when the application
  615.     quits, we will allocate its space here, before anything that might be a locked
  616.     relocatable object gets into the heap. This way, we can force the storage to be
  617.     in the lowest memory available in the heap. Window storage can differ widely
  618.     amongst applications depending on how many windows are created and disposed. */
  619.  
  620. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  621.     this module. If an error is detected, instead of merely doing an ExitToShell,
  622.     which leaves the user without much to go on, we call AlertUser, which puts
  623.     up a simple alert that just says an error occurred and then calls ExitToShell.
  624.     Since there is no other cleanup needed at this point if an error is detected,
  625.     this form of error- handling is acceptable. If more sophisticated error recovery
  626.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  627.  
  628. #pragma segment Initialize
  629. void Initialize()
  630. {
  631.     Handle        menuBar;
  632.     WindowPtr    window;
  633.     long        total, contig;
  634.     EventRecord event;
  635.     short        count;
  636.  
  637.     gInBackground = false;
  638.  
  639.     InitGraf((Ptr) &qd.thePort);
  640.     InitFonts();
  641.     InitWindows();
  642.     InitMenus();
  643.     TEInit();
  644.     InitDialogs(nil);
  645.     InitCursor();
  646.     
  647.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  648.          if you are using it. */
  649.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  650.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  651.         of checking for port availability themselves. */
  652.     
  653.     /*    This next bit of code is necessary to allow the default button of our
  654.         alert be outlined.
  655.         1.02 - Changed to call EventAvail so that we don't lose some important
  656.         events. */
  657.      
  658.     for (count = 1; count <= 3; count++)
  659.         EventAvail(everyEvent, &event);
  660.     
  661.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  662.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  663.         call to SysEnvirons by calling it after initializing AppleTalk. */
  664.      
  665.     SysEnvirons(kSysEnvironsVersion, &gMac);
  666.     
  667.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  668.     
  669.     if (gMac.machineType < 0) AlertUser();
  670.     
  671.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  672.         in TrapAvailable if a tool trap value is out of range. */
  673.         
  674.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  675.  
  676.  
  677.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  678.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  679.         MultiFinder we needed. This did not work well because it assumed too much about
  680.         the relationship between what we asked MultiFinder for and what we would actually
  681.         get back, as well as how to measure it. Instead, we will use an alternate
  682.         method comprised of two steps. */
  683.      
  684.     /*    It is better to first check the size of the application heap against a value
  685.         that you have determined is the smallest heap the application can reasonably
  686.         work in. This number should be derived by examining the size of the heap that
  687.         is actually provided by MultiFinder when the minimum size requested is used.
  688.         The derivation of the minimum size requested from MultiFinder is described
  689.         in Sample.h. The check should be made because the preferred size can end up
  690.         being set smaller than the minimum size by the user. This extra check acts to
  691.         insure that your application is starting from a solid memory foundation. */
  692.      
  693.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  694.     
  695.     /*    Next, make sure that enough memory is free for your application to run. It
  696.         is possible for a situation to arise where the heap may have been of required
  697.         size, but a large scrap was loaded which left too little memory. To check for
  698.         this, call PurgeSpace and compare the result with a value that you have determined
  699.         is the minimum amount of free memory your application needs at initialization.
  700.         This number can be derived several different ways. One way that is fairly
  701.         straightforward is to run the application in the minimum size configuration
  702.         as described previously. Call PurgeSpace at initialization and examine the value
  703.         returned. However, you should make sure that this result is not being modified
  704.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  705.         PurgeSpace. Make sure to remove that call before shipping, though. */
  706.     
  707.     /* ZeroScrap(); */
  708.  
  709.     PurgeSpace(&total, &contig);
  710.     if (total < kMinSpace) AlertUser();
  711.  
  712.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  713.         to check memory is that we can now give the user an alert to tell him/her what
  714.         happened. Although it is possible that the memory situation could be worsened by
  715.         displaying an alert, MultiFinder would gracefully exit the application with
  716.         an informative alert if memory became critical. Here we are acting more
  717.         in a preventative manner to avoid future disaster from low-memory problems. */
  718.  
  719.     /* New code to quit if system configuration is not right <MC> */
  720.     CheckSystemConfiguration ();
  721.  
  722.     /*     we will allocate our own window storage instead of letting the Window
  723.         Manager do it because GetNewWindow may load in temp. resources before
  724.         making the NewPtr call, and this can lead to heap fragmentation. */
  725.     if (gMac.hasColorQD) {                                        /* Color window if possible <MC> */
  726.         window = (WindowPtr) NewPtr(sizeof(CWindowRecord));
  727.         if ( window == nil ) AlertUser();
  728.         window = GetNewCWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  729.     } else {
  730.         window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  731.         if ( window == nil ) AlertUser();
  732.         window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  733.     }
  734.         
  735.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  736.     if ( menuBar == nil ) AlertUser();
  737.     SetMenuBar(menuBar);                    /* install menus */
  738.     DisposHandle(menuBar);
  739.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  740.     DrawMenuBar();
  741.     
  742.     Initialize3D (window);        /* Initialize Graf3D, etc <MC> */
  743.     
  744. } /*Initialize*/
  745.  
  746.  
  747. /*    This utility loads the global rectangles that are used by the window
  748.     drawing routines. It shows how the resource manager can be used to hold
  749.     values in a convenient manner. These values are then easily altered without
  750.     having to re-compile the source code. In this particular case, we know
  751.     that this routine is being called at initialization time. Therefore,
  752.     if a failure occurs here, we will assume that the application is in such
  753.     bad shape that we should just exit. Your error handling may differ, but
  754.     the check should still be made. */
  755.     
  756. #pragma segment Initialize
  757. Boolean GoGetRect( short rectID, Rect *theRect )
  758. {
  759.     Handle        resource;
  760.     
  761.     resource = GetResource('RECT', rectID);
  762.     if ( resource != nil ) {
  763.         *theRect = **((Rect**) resource);
  764.         return true;
  765.     }
  766.     else
  767.         return false;
  768. } /* GoGetRect */
  769.  
  770.  
  771. /*    Check to see if a window belongs to the application. If the window pointer
  772.     passed was NIL, then it could not be an application window. WindowKinds
  773.     that are negative belong to the system and windowKinds less than userKind
  774.     are reserved by Apple except for windowKinds equal to dialogKind, which
  775.     mean it is a dialog.
  776.     1.02 - In order to reduce the chance of accidentally treating some window
  777.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  778.     is userKind. If you add different kinds of windows to Sample you'll need
  779.     to change how this all works. */
  780.  
  781. #pragma segment Main
  782. Boolean IsAppWindow(window)
  783.     WindowPtr    window;
  784. {
  785.     short        windowKind;
  786.  
  787.     if ( window == nil )
  788.         return false;
  789.     else {    /* application windows have windowKinds = userKind (8) */
  790.         windowKind = ((WindowPeek) window)->windowKind;
  791.         return (windowKind == userKind);
  792.     }
  793. } /*IsAppWindow*/
  794.  
  795.  
  796. /* Check to see if a window belongs to a desk accessory. */
  797.  
  798. #pragma segment Main
  799. Boolean IsDAWindow(window)
  800.     WindowPtr    window;
  801. {
  802.     if ( window == nil )
  803.         return false;
  804.     else    /* DA windows have negative windowKinds */
  805.         return ((WindowPeek) window)->windowKind < 0;
  806. } /*IsDAWindow*/
  807.  
  808.  
  809. /*    Check to see if a given trap is implemented. This is only used by the
  810.     Initialize routine in this program, so we put it in the Initialize segment.
  811.     The recommended approach to see if a trap is implemented is to see if
  812.     the address of the trap routine is the same as the address of the
  813.     Unimplemented trap. */
  814. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  815.     if a ToolTrap is out of range of a pre-MacII ROM. */
  816.  
  817. #pragma segment Initialize
  818. Boolean TrapAvailable( short tNumber, TrapType tType )
  819. {
  820.     if ( ( tType == ToolTrap ) &&
  821.         ( gMac.machineType > envMachUnknown ) &&
  822.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  823.         tNumber = tNumber & 0x03FF;
  824.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  825.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  826.     }
  827.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  828. } /*TrapAvailable*/
  829.  
  830.  
  831. /*    Display an alert that tells the user an error occurred, then exit the program.
  832.     This routine is used as an ultimate bail-out for serious errors that prohibit
  833.     the continuation of the application. Errors that do not require the termination
  834.     of the application should be handled in a different manner. Error checking and
  835.     reporting has a place even in the simplest application. The error number is used
  836.     to index an 'STR#' resource so that a relevant message can be displayed. */
  837.  
  838. #pragma segment Main
  839. void AlertUser()
  840. {
  841.     short        itemHit;
  842.  
  843.     SetCursor(&qd.arrow);
  844.     itemHit = Alert(rUserAlert, nil);
  845.     ExitToShell();
  846. } /* AlertUser */